package com.example.huhaichao.music;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.huhaichao.music.database.DBService;
import com.example.huhaichao.music.fragment.AllMusic;
import com.example.huhaichao.music.fragment.FavoriteMusic;
import com.example.huhaichao.music.fragment.SearchMusic;
import com.example.huhaichao.music.service.MusicService;
import com.example.huhaichao.music.util.MusicUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity implements AllMusic.Callbacks, FavoriteMusic.Callbacks2, SearchMusic.Callbacks3, View.OnClickListener {
    private ViewPager mViewPager;
    private RadioGroup mRadioGroup;
    private TextView musicTime, musicTotal;
    private SeekBar seekBar;
    private ImageButton btn_playPre, btn_play, btn_playNext, btn_favorite;
    private SimpleDateFormat time = new SimpleDateFormat("mm:ss");

    private boolean tag1 = false;
    private boolean tag2 = false;
    private MusicService musicService;
    private int playPosition;
    private DBService dbService;
    public List<Fragment> mFragments = new ArrayList<>();
    private static final String TAG = "MainActivity";


    //  在Activity中调用 bindService 保持与 Service 的通信
    private void bindServiceConnection() {
        Intent intent = new Intent(MainActivity.this, MusicService.class);
        startService(intent);
        bindService(intent, serviceConnection, this.BIND_AUTO_CREATE);
    }

    //  回调onServiceConnected 函数，通过IBinder 获取 Service对象，实现Activity与 Service的绑定
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicService = ((MusicService.MyBinder) (service)).getService();
            musicService.setMainActivity(MainActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicService = null;
        }
    };

    public void allowBindService() {
        getApplicationContext().bindService(new Intent(this, MusicService.class),
                serviceConnection,
                Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbService = new DBService(this);
        findViewById();
        setListener();
        bindServiceConnection();
        List<Fragment> mFragments = initFragment();
        mViewPager.setAdapter(new MyPageAdapter(getSupportFragmentManager(), mFragments));
        mRadioGroup.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
        mViewPager.setCurrentItem(1);//指定页面
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser == true) {
                    musicService.mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    //  通过 Handler 更新 UI 上的组件状态
    public Handler handler = new Handler();
    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (musicService.mediaPlayer != null) {
                musicTime.setText(time.format(musicService.mediaPlayer.getCurrentPosition()));
                seekBar.setProgress(musicService.mediaPlayer.getCurrentPosition());
                seekBar.setProgress(musicService.getCurrentPosition());
                seekBar.setMax(musicService.mediaPlayer.getDuration());
                musicTotal.setText(time.format(musicService.mediaPlayer.getDuration()));
                handler.postDelayed(runnable, 200);
            }
        }
    };

    //重置控件
    public void resetUI() {
        Log.d(TAG, "resetUI: " + "-----");
        musicTime.setText("00:00");
        musicTotal.setText("00:00");
        seekBar.setProgress(0);
        btn_play.setImageResource(R.drawable.player_pause);
    }

    public void findViewById() {
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mRadioGroup = (RadioGroup) findViewById(R.id.group);
        musicTime = (TextView) findViewById(R.id.musictime);
        musicTotal = (TextView) findViewById(R.id.musictotal);
        seekBar = (SeekBar) findViewById(R.id.musicseekbar);

        btn_playPre = (ImageButton) findViewById(R.id.btn_playPre);
        btn_play = (ImageButton) findViewById(R.id.btn_play);
        btn_playNext = (ImageButton) findViewById(R.id.btn_playNext);
        btn_favorite = (ImageButton) findViewById(R.id.btn_favorite);

    }

    public void setListener() {
        btn_playPre.setOnClickListener(this);
        btn_play.setOnClickListener(this);
        btn_playNext.setOnClickListener(this);
        btn_favorite.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_playPre://上一首
                if (musicService.getUrlPlaying() != null) {
                    musicService.preMusic(playPosition);
                }
                break;
            case R.id.btn_play://播放
                if (musicService.getUrlPlaying() != null) {
                   playControl();
                }
                break;
            case R.id.btn_playNext://下一首
                if (musicService.getUrlPlaying() != null) {
                    musicService.nextMusic(playPosition);
                }
                break;
            case R.id.btn_favorite:
                // Fragment fm=getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":"+viewpager.getCurrentItem());
                if (musicService.getUrlPlaying() != null) {
                    FavoriteMusic fm = (FavoriteMusic) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":1");
                    if (!isLove()) {
                        //添加收藏
                        Log.d(TAG, "onClick: 添加收藏");
                        dbService.myInsert("insert into Musics(musicUrl)values(?)", new String[]{musicService.getUrlPlaying()});
                        MusicUtils.mMusicList.add(musicService.getUrlPlaying());
                        fm.update(1, musicService.getUrlPlaying());
                        btn_favorite.setImageResource(R.drawable.icon_favorite_on);
                    } else {
                        //取消收藏
                        Log.d(TAG, "onClick: 取消收藏");
                        dbService.myDelete(musicService.getUrlPlaying());
                        MusicUtils.mMusicList.remove(musicService.getUrlPlaying());
                        fm.update(2, musicService.getUrlPlaying());
                        btn_favorite.setImageResource(R.drawable.icon_favorite);
                    }
                }

        }
    }


    /**
     * 初始化Fragment数据
     */
    private List<Fragment> initFragment() {
        AllMusic f1 = new AllMusic();
        FavoriteMusic f2 = new FavoriteMusic();
        SearchMusic f3 = new SearchMusic();
        //List<Fragment> mFragments = new ArrayList<>();
        mFragments.add(f1);
        mFragments.add(f2);
        mFragments.add(f3);
        return mFragments;
    }

    //fragment1
    @Override
    public void onItemSelected(int id) {
        Log.d(TAG, "which fragment: " + mViewPager.getCurrentItem());
        tag1 = false;
        tag2 = false;
        musicService.tag = false;
        playPosition = id;
        musicService.playMusic(playPosition, mViewPager.getCurrentItem());
        isLove();
        playControl();//播放和暂停控制
    }

    //fragment2
    @Override
    public void onItemSelectedFavorite(int id) {
        Log.d(TAG, "which fragment: " + mViewPager.getCurrentItem());
        tag1 = false;
        tag2 = false;
        musicService.tag = false;
        playPosition = id;
        musicService.playMusic(playPosition, mViewPager.getCurrentItem());
        isLove();
        playControl();
    }

    //fragment2
    @Override
    public void onItemSelectedSearch(int id) {
        Log.d(TAG, "which fragment: " + mViewPager.getCurrentItem());
        tag1 = false;
        tag2 = false;
        musicService.tag = false;
        playPosition = id;
        musicService.playMusic(playPosition, mViewPager.getCurrentItem());
        isLove();
        playControl();
    }

    class MyPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> mFragments;

        public MyPageAdapter(FragmentManager fm, List<Fragment> mFragments) {
            super(fm);
            this.mFragments = mFragments;
        }

        @Override
        public Fragment getItem(int i) {
            return mFragments.get(i);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }
    }


    /**
     * 底部按钮选择的事件处理
     */
    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            int currentIndex = 0;
            switch (checkedId) {
                case R.id.one:
                    currentIndex = 0;
                    break;
                case R.id.two:
                    currentIndex = 1;
                    break;
                case R.id.three:
                    currentIndex = 2;
                    break;
            }
            if (mViewPager.getCurrentItem() != currentIndex) {
                mViewPager.setCurrentItem(currentIndex);
            }
        }
    }

    /**
     * Fragment 选择事件
     */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
        }

        @Override
        public void onPageSelected(int i) {
            int currentIndex = mViewPager.getCurrentItem();
            switch (currentIndex) {
                case 0:
                    mRadioGroup.check(R.id.one);
                    break;
                case 1:
                    mRadioGroup.check(R.id.two);
                    break;
                case 2:
                    mRadioGroup.check(R.id.three);
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {
        }
    }

    //每次点击列表播放时，判断是否已收藏，设置爱心图片
    public boolean isLove() {
        Cursor cursor = dbService.myQuery("select musicUrl from Musics where musicUrl like ?", new String[]{musicService.getUrlPlaying()});
        if (cursor.getCount() == 0) {
            btn_favorite.setImageResource(R.drawable.icon_favorite);
            return false;
        }
        btn_favorite.setImageResource(R.drawable.icon_favorite_on);
        return true;
    }

    //播放和暂停控制
    public void playControl() {
        if (musicService.mediaPlayer != null) {
            seekBar.setProgress(musicService.mediaPlayer.getCurrentPosition());
            seekBar.setMax(musicService.mediaPlayer.getDuration());
        }

        //  由tag的变换来控制事件的调用
        if (musicService.tag != true) {
            btn_play.setImageResource(R.drawable.player_pause);
            musicService.tag = true;
            if (tag1 == false) {
                tag1 = true;
            }
        } else {
            btn_play.setImageResource(R.drawable.player_play);
            musicService.tag = false;
        }
        if (tag2 == false) {
            handler.post(runnable);
            tag2 = true;
        }
    }
}
